﻿using System;
using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using Growatt.ShinebusService.Helper;
using Growatt.ShinebusService.Model;
using Growatt.UploadPacktest;
using TestFile.Model;

namespace TestFile
{
    public class GetOAFileUrlsHelper
    {
        private readonly IHttpClientFactory _httpClientFactory;

        public GetOAFileUrlsHelper(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public async Task<FirmwareUploadInfoResponse> GetOAFileUrls(List<string> strings, string Directory)
        {
            // RSA公钥字符串

            string appid = "17762465-0ae6-1ee6-80ff-db1c93e890eb";
            string secret = "dfb2d4c5-ca32-4497-b916-2b804704449a"; //通过spk对secret进行加密后的密文。（RSA加密）
            string userid = "1"; //通过spk公钥对userid进行RAS加密生成的密文

            // 使用公钥对secret进行加密
            string encryptedSecret = encryptedBase64(secret);

            // 调用获取OA token的接口
            string token = await GetOATokenAsync(appid, encryptedSecret);

            // 使用公钥对userid进行加密
            string encryptedUserId = encryptedBase64(userid);

            // 请求的文件名列表
            string[] fileNamesWithNoExtension = strings.ToArray().Select(o => o.Split('.')[0]).ToArray();
            string[] fileNames = strings.ToArray().Select(o => o.Split('.')[1]).ToArray(); //获取文件扩展名
            try
            {
                string jsonResponse = await new FileUrlService(this._httpClientFactory).GetFileUrlsAsync(appid, token, encryptedUserId, fileNamesWithNoExtension);

                // 解析 JSON 响应
                FileUrlResponse response = FileUrlService.ParseJsonResponse(jsonResponse);
                // 验证响应状态
                FileUrlService.ValidateResponse(response);
                // 输出文件信息
                Console.WriteLine("文件信息:");
                int index = 0;
                foreach (var file in response.Data)
                {
                    Console.WriteLine($"文件名称: {file.FileName}");
                    Console.WriteLine($"文件下载路径: {file.FileUrl}");
                    // 指定本地保存路径
                    string destinationPath = Path.Combine(Directory, file.FileName + "." + fileNames[index]);
                    // 下载文件
                    var result = await new FileDownloader(this._httpClientFactory).DownloadFileAsync(file.FileUrl, destinationPath);
                    if (result.UploadStatus == 0)
                    {
                        return new FirmwareUploadInfoResponse(string.Empty, 0, "下载文件时出错!");
                    }
                    index++;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"请求失败: {ex.Message}");
                return new FirmwareUploadInfoResponse(string.Empty, 0, $"OA请求下载文件请求失败: {ex.Message}");
            }
            return new FirmwareUploadInfoResponse(string.Empty, 1, $"下载文件成功!");
        }

        public async Task<string> GetOATokenAsync(string appid, string encryptedSecret)
        {
            string requestUrl = "http://oa.growatt.com:88/api/ec/dev/auth/applytoken";
            string requestJson = $"{{\"appid\": \"{appid}\", \"secret\": \"{encryptedSecret}\"}}";

            using (HttpClient client = _httpClientFactory.CreateClient("OSS"))
            {
                client.DefaultRequestHeaders.Add("appid", appid);
                client.DefaultRequestHeaders.Add("secret", encryptedSecret);
                HttpContent content = new StringContent(requestJson, Encoding.UTF8, "application/json");

                HttpResponseMessage response = await client.PostAsync(requestUrl, content);
                string responseBody = await response.Content.ReadAsStringAsync();

                // 解析响应JSON以获取token
                dynamic responseObject = DuiHelperJson.JsonToObject(responseBody);
                if (responseObject.status == true)
                {
                    return responseObject.token;
                }
                else
                {
                    throw new Exception("获取token失败: " + responseObject.msg);
                }
            }
        }

        public static string encryptedBase64(string plaintext)
        {
            string publicKeyPem =
                @"-----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAslM/FhKbWUA/3m2ypKUl
    65mAkyEmmvk4rgmuJMO5pZpZv/kk0hxRiABTYtvXGFnJW94c9VUy2YmW+xjU5DPB
    bPCQsZ3A0i2MKVazhyua943F12e58Ym7fH/VHOXyuwrxwddF7sHYnJ1Tr0QNSzay
    9nJspWgmb4hiESm5DlwGHNjQ6s8gjMN+FwNdG6sKkg2b1UiT3s2m1nsYX7H8INiv
    AbHrsMIzoV8lQgndRCl/YzEMpZsdo8LmKVCl1jziH6efYhNGE1I4yIi8yDiViMlF
    l3C7ohO8R2xYPDtVuxOR6QnTLOx3piNiUwBvscScJXbz3rBjDmricZV/vSKL2+Fo
    AwIDAQAB
    -----END PUBLIC KEY-----";

            try
            {
                using (RSA rsa = RSA.Create())
                {
                    rsa.ImportFromPem(publicKeyPem);
                    byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
                    byte[] encryptedBytes = rsa.Encrypt(plaintextBytes, RSAEncryptionPadding.Pkcs1);
                    string encryptedBase64 = Convert.ToBase64String(encryptedBytes);
                    return encryptedBase64;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"公钥加载失败: {ex.Message}");
            }
            return plaintext;
        }
    }
}
